#!/usr/bin/env python
#-*- coding: utf-8 -*-
#
# Copyright 2013 Antoine Drouin (poinix@gmail.com)
#
# This file is part of PAT.
#
#    PAT is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    PAT is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with PAT.  If not, see <http://www.gnu.org/licenses/>.
#

"""
 State feedback stabilization for the planar VTOL vehicle
"""

import numpy as np
import matplotlib.pyplot as plt

import pat.vehicles.rotorcraft.dynamic_model_planar_simple as dm
import pat.utils as pu

my_dm = dm.DynamicModel()
Xe, Ue = my_dm.trim({'x':4, 'z':3})

dt = 0.01; time = np.arange(0., 5., dt)
X = np.zeros((len(time), dm.sv_size))
X[0] = my_dm.reset()
U = np.zeros((len(time), dm.iv_size))

K=np.array([[0., 0., -0.2, 0., 0., -0.1],
            [0., 0.,  0.2, 0., 0.,  0.1]])

for i in range(1,len(time)):
    U[i-1] = Ue - np.dot(K, X[i-1])
    X[i] = my_dm.run(dt, U[i-1])

U[-1] = U[-2]

my_dm.plot_state(time, X, U,  window_title="State feedback stabilization for the planar VTOL vehicle")

A, B = my_dm.jacobian(Xe, Ue)
wol, Mol = np.linalg.eig(A)
Acl = A - np.dot(B, K)
wcl, Mcl = np.linalg.eig(Acl)

np.set_printoptions(precision=2, suppress=True, linewidth=200)
text1 = '''
A
{:s}
'''.format(A)
text2 = '''
B
{:s}
'''.format(B)
text3 = '''
Open loop poles : {:s}
'''.format(wol)
text4 = '''
Gain:
{:s}
Closed Loop Poles: {:s}
Closed loop eigenvectors:
{:s}
'''.format(K, wcl, Mcl)
pu.write_text(3, 3, 8, (text1, text2, text3, text4),   colspan=2, loc=[[0.1, 9.7],[2.5, 9.7],[0.5, 3.],[4., 9.7]],
              filename="../doc/images/wiki/planar_vtol_state_feedback_1.png")

plt.show()
